import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import morgan from 'morgan';
import rateLimit from 'express-rate-limit';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import { createRequire } from 'module';
import auditorRoutes from './routes/auditorRoutes.js';

// 加载环境变量
dotenv.config();

// 获取当前文件的目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 导入路由
import travelRoutes from './routes/travelRoutes.js';

// 使用createRequire导入CommonJS模块
const require = createRequire(import.meta.url);
const ossRouter = require('./routes/oss.cjs');

class App {
  constructor() {
    this.app = express();
    this.configureBasicMiddlewares(); // 恢复基本中间件配置
    this.setupRoutes();
  }

  configureBasicMiddlewares() {
    // 只配置必要的基本中间件
    this.app.use(express.json());
    this.app.use(express.urlencoded({ extended: true }));

    // 配置CORS以允许跨域请求
    this.app.use(cors({
      origin: ['http://localhost:5174'],
      credentials: true
    }));
  }

  setupRoutes() {
    // API路由
    this.app.use('/api/auditors', auditorRoutes);
    this.app.use('/api/travels', travelRoutes);
    this.app.use('/api/oss', ossRouter);

    // 添加路由测试端点
    this.app.get('/api/test', (req, res) => {
      res.json({ message: 'API测试端点正常工作' });
    });

    // 根路由 - API健康检查
    this.app.get('/', (req, res) => {
      res.json({
        message: '旅游日记平台API服务运行正常',
        version: '0.1.0',
        timestamp: new Date().toISOString()
      });
    });

    // 处理404
    this.app.use((req, res) => {
      res.status(404).json({
        success: false,
        error: '请求的资源不存在'
      });
    });
  }

  start(port = process.env.PORT || 3000) {
    this.app.listen(port, () => {
      console.log(`服务器运行在 http://localhost:${port}`);
      console.log(`API服务已启动，版本: 0.1.0`);
      console.log(`环境: ${process.env.NODE_ENV || 'development'}`);
      console.log(`OSS服务端点: http://localhost:${port}/api/oss/get_sts_token_for_oss_upload`);

      // 打印环境变量是否存在（不打印实际值，保护敏感信息）
      console.log(`OSS_ACCESS_KEY_ID是否配置: ${process.env.OSS_ACCESS_KEY_ID ? '已配置' : '未配置'}`);
      console.log(`OSS_ACCESS_KEY_SECRET是否配置: ${process.env.OSS_ACCESS_KEY_SECRET ? '已配置' : '未配置'}`);
    });
  }
}

const app = new App().app;
const server = new App();
server.start();

export default app;